﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using Microsoft.Win32;
using NewLife.Data;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using UIWindows.Commands;
using UIWindows.Domains;
using UIWindows.Enums;
using UIWindows.GlobalStatics;
using UIWindows.Models;
using UIWindows.Models.ParameterModels;
using UIWindows.Tools.Helper;
using UIWindows.ViewModels.Dialogs;
using UIWindows.Views;
using UIWindows.Views.DeviceInteractiveaddressItems;
using XCode;
using XingLucifer.IBase.Enums;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace UIWindows.ViewModels
{
    public class MainWindowViewModel : ViewModelBase
    {
        private object _viewContent;

        public object ViewContent
        {
            get { return _viewContent; }
            set => SetProperty(ref _viewContent, value);
        }

        //private bool _isShowWarnTip;

        //public bool IsShowWarnTip
        //{
        //    get { return _isShowWarnTip; }
        //    set => SetProperty(ref _isShowWarnTip, value);
        //}

        /// <summary>
        /// 运行时间
        /// </summary>
        public DateTime RunTime { get => DateTime.Now; }

        public ObservableCollection<MenuModel> ContentList { get; set; }

        private MenuModel _selectedItem;

        public MenuModel SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                if (value != null && _selectedItem != value)
                {
                    var ucs = ObjectContainer.ResolveSingleton<UserConfigStatic>();
                    if (value.Name == "系统配置" && ucs.LoginUser.Level != AuthorityTypes.超级管理员)
                    {
                        "此页面不可操作！！！".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                        _selectedItem = null;
                        return;
                    }
                    if (value.Name == "主 页" || ucs.LoginUser.Name != "未登录")
                    {
                        _selectedItem = value;
                        ViewContent = ObjectContainer.ResolvePage(value.Name);
                    }
                    else
                    {
                        "请登录，方可继续操作".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                        _selectedItem = null;
                    }
                }
            }
        }

        public UserConfigStatic UserConfig { get; set; }
        public GlobalStatics.SystemConfigStatic SystemConfig { get; set; }
        public ParameterStatic Parameter { get; set; }
        public TemporaryStatic Temporary { get; set; }
        public DeviceConfigStatic DeviceConfig { get; set; }
        public DeviceInteractiveaddressStatic DeviceInteractiveaddressConfig { get; set; }

        private ReserveStatic Reserve { get; set; }

        private DisplayItemsStatic _displayItems;
        public MainWindowViewModel()
        {
           
            SystemConfig = ObjectContainer.ResolveSingleton<SystemConfigStatic>();
            UserConfig = ObjectContainer.ResolveSingleton<UserConfigStatic>();
            _displayItems = ObjectContainer.ResolveSingleton<DisplayItemsStatic>();
            Parameter = ObjectContainer.ResolveSingleton<ParameterStatic>();
            Temporary = ObjectContainer.ResolveSingleton<TemporaryStatic>();
            //Temporary = ObjectContainer.ResolveSingleton<TemporaryStatic>();
            DeviceConfig = ObjectContainer.ResolveSingleton<DeviceConfigStatic>();

            DeviceInteractiveaddressConfig = ObjectContainer.ResolveSingleton<DeviceInteractiveaddressStatic>();

            UserConfig.UpdateMenu += UpdateMenu;
            ContentList = new ObservableCollection<MenuModel>();


            Reserve = ObjectContainer.ResolveSingleton<ReserveStatic>();

            SystemConfig.SCM.IsShowWarnTip = true;

            SystemConfig.SCM.HomeMessage = "当前上位机未运行，请点击右上角运行按钮";

            #region 主题样式
            _topicsModel = !File.Exists(GlobalStatic.TopicsPath) ? new TopicsModel() : JsonSerializer.Deserialize<TopicsModel>(File.ReadAllText(GlobalStatic.TopicsPath, Encoding.UTF8));

            ITheme theme = _paletteHelper.GetTheme();
            _primaryColor = _topicsModel.PrimaryColor ?? theme.PrimaryMid.Color;
            _secondaryColor = _topicsModel.SecondaryColor ?? theme.SecondaryMid.Color;
            if (theme is Theme internalTheme && internalTheme.ColorAdjustment != null)
            {
                internalTheme.ColorAdjustment.Colors = ColorSelection.All;
            }
            SelectedColor = _topicsModel.PrimaryColor;
            ChangeCustomColor((Color)_primaryColor);
            _paletteHelper.ApplyBase(_topicsModel.IsDarkTheme);
            #endregion
            foreach (var item in ObjectContainer.GetMenuList(AuthorityTypes.ALL))
            {
                if (!_displayItems.RoleInit.Any(x => x.RoleName == item.Name) && item.Name != "系统配置")
                {
                    _displayItems.RoleInit.Add(new RoleInitModel()
                    {
                        IsEnable = true,
                        Authority = AuthorityTypes.操作员,
                        Category = "菜单",
                        RoleName = item.Name,
                    });
                    _displayItems.RoleInit.Add(new RoleInitModel()
                    {
                        IsEnable = true,
                        Authority = AuthorityTypes.工艺,
                        Category = "菜单",
                        RoleName = item.Name,
                    });
                    _displayItems.RoleInit.Add(new RoleInitModel()
                    {
                        IsEnable = true,
                        Authority = AuthorityTypes.设备,
                        Category = "菜单",
                        RoleName = item.Name,
                    });
                }
            }
            UpdateMenu(AuthorityTypes.ALL);

            if (SystemConfig.SCM.MainDeviceType == MainDeviceTypeEnum.后段组装线)
            {
                try
                {
                    Task.Run(async () =>
                    {
                        //Action<string, MessageLevelType> _log = DialogLogHelper.RunLog;

                        await Kinlo.WebApi.Program.StartService(9999, DialogLogHelper.RunLog); // 替换为你的端口  


                        Console.WriteLine();
                    });


                }
                catch (Exception ex)
                {
                    Console.WriteLine();
                }

                try
                {
                    var _plateParameter = Parameter.MESCollectionItemsParameter[MachineInfoTypes.预充装盘];
                    if (_plateParameter.TrayBarcode != Reserve.PlateScanBarcodeStatic.TrayBarcode)
                    {
                        $"预防保护托盘码{Reserve.PlateScanBarcodeStatic.TrayBarcode}不等于当前托盘码{_plateParameter.TrayBarcode}".RunLog(MessageLevelType.警告);
                        $"当前托盘码已替换{_plateParameter.TrayBarcode}=>{Reserve.PlateScanBarcodeStatic.TrayBarcode}".RunLog(MessageLevelType.警告);
                        $"当前托盘码流水ID已替换{_plateParameter.TrayBarcodeID}=>{Reserve.PlateScanBarcodeStatic.TrayBarcodeID}".RunLog(MessageLevelType.警告);
                        _plateParameter.TrayBarcode = Reserve.PlateScanBarcodeStatic.TrayBarcode;
                        _plateParameter.TrayBarcodeID = Reserve.PlateScanBarcodeStatic.TrayBarcodeID;
                    }
                    Temporary.mesCollectionItemsTemporary[(int)MachineInfoTypes.预充装盘].TrayBarcode = _plateParameter.TrayBarcode;
                }
                catch (Exception ex)
                {

                    $"当前托盘码检测保护报错{ex}".RunLog(MessageLevelType.警告);
                }
            }

            //UserConfig.Login("admin", "12345678");
            UserConfig.Login("生产", "123456");


        }

        /// <summary>
        /// 更新菜单
        /// </summary>
        /// <param name="authority"></param>
        public void UpdateMenu(AuthorityTypes authority)
        {
            ContentList.Clear();
            foreach (var item in ObjectContainer.GetMenuList(authority))
            {
                if (_displayItems.RoleInit.Any(x => x.RoleName == item.Name && x.Authority == authority && x.IsEnable)
                    || AuthorityTypes.ALL == authority
                    || AuthorityTypes.管理员 == authority
                    || AuthorityTypes.超级管理员 == authority)
                {
                    ContentList.Add(item);
                }
            }
            if (ContentList.Count > 0) SelectedItem = ContentList[0];
        }

        public DelegateCommand HelperButton => new DelegateCommand(() =>
        {
            _ = MaterialDesignThemes.Wpf.DialogHost.Show(new Views.Dialogs.LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);
        });

        public DelegateCommand Login => new DelegateCommand(() =>
        {
            _ = DialogHost.Show(new Views.Dialogs.LoginDialogs() { DataContext = new LoginDialogsViewModel(UserConfig) }, PopUpTypes.Global.ToString()).ConfigureAwait(false);
        });
        private IMESInteraction _interaction;
        public DelegateCommand<Button> PerformTask => new DelegateCommand<Button>(async sender =>
        {
            string tableName = $"CoilCoreLoadingData_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}";

            CoilCoreLoadingData.Meta.TableName = tableName;

            //var fd = CoilCoreLoadingData.Meta.Table.FindByName(CoilCoreLoadingData.__.AcquisitionTime);
            //object list;
            //var dataList = CoilCoreLoadingData.FindAll(null, fd.Desc(), null, 0, 1).ToList();
            //if(dataList.Count > 0)
            //{
            //    list = dataList[0];
            //}


            if (SystemConfig.SCM.PerformTaskName == null)
            {
                SystemConfig.SCM.PerformTaskName = sender;
            }
    
            _ = DialogHost.Show(new Views.Dialogs.LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);
            // 使用十六进制颜色代码创建颜色
            Color customColor = (Color)ColorConverter.ConvertFromString("#67C23A");

            if (SystemConfig.SCM.PerformTaskName.Content.ToString() == "    运  行    ")
            {
                var serviceList = Temporary.LinkList.FirstOrDefault(x => x.ServiceName == "设备状态");
                if (serviceList != null && !serviceList.Status)
                {
                    _ = "有设备网线通信不上,查看日志系统输出信息,检查对应设备网线连接!!!".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                    return;
                }

                if (await Services.TaskService.Instance.SwitchOn())
                {
                    SystemConfig.SCM.PerformTaskName.Content = "    停  止    ";
                    if (DialogHost.IsDialogOpen(PopUpTypes.Global.ToString())) DialogHost.Close(PopUpTypes.Global.ToString());

                    SystemConfig.SCM.IsShowWarnTip = false;
                    customColor = (Color)ColorConverter.ConvertFromString("#F56C6C");
                    SystemConfig.SCM.PerformTaskName.Background = new SolidColorBrush(customColor);
                }
            }
            else
            {
                Services.TaskService.Instance.SwitchOFF();
                SystemConfig.SCM.IsShowWarnTip = true;
                SystemConfig.SCM.PerformTaskName.Background = new SolidColorBrush(customColor);
            }
        });

        /// <summary>
        /// 清除计时
        /// </summary>
        public DelegateCommand ClearTime => new DelegateCommand(() =>
        {
            var model = ObjectContainer.ResolveSingleton<HomeStatic>();
            model.EquipmentTime.Run = 0;
            model.EquipmentTime.Manual = 0;
            model.EquipmentTime.Error = 0;
            model.SaveEquipmentTime();
        });



        public DelegateCommand ExitLogin => new DelegateCommand(() => UserConfig.ExitLogin());
        /// <summary>
        /// 下班上传产量给MES并清空产量
        /// </summary>
        public DelegateCommand ProductionUploadMES => new DelegateCommand(() =>
        {
       

            if (SystemConfig.SCM.IsShowWarnTip!=false||SystemConfig.SCM.PerformTaskName?.Content.ToString() == "    运  行    ")
            {
                _ = "请先点击运行，运行成功后，才能获取产量上传".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
                return;
            }

            if (MessageBox.Show("确定要下班产量上传MES并清空产量吗？", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
            {
                return;
            }
            var plcDataList = DeviceConfig.DeviceList.Where(x=>x.DeviceType==DeviceTypes.KVPLC).ToList();

            var mesData_HourInteraction = new MESProductCountData_Hour(DialogLogHelper.MesLog
            , DialogLogHelper.MESDialog);

            var mesData_DayInteraction = new MESProductCountData_Day(DialogLogHelper.MesLog
            , DialogLogHelper.MESDialog);
            int sta = 1;
            string errorMachine = "";
            foreach (var plcItem in plcDataList)
            {
                if (plcItem.Index == 999)
                {
                    $"{plcItem.ServiceName}设备未启用，不做清零处理".RunLog(MessageLevelType.警告);
                    continue;
                }
                if (plcItem.PLC!=null)
                {
                    try
                    {
                      
                        var InjMachine = plcItem.PLC;
                        var machineInfoType = (MachineInfoTypes)Enum.Parse(typeof(MachineInfoTypes), plcItem.ServiceName);
                        if(machineInfoType== MachineInfoTypes.预充装盘)
                        {
                            MESCountUpLoad_Hour();
                            continue;
                        }
                        if (DeviceInteractiveaddressConfig.BaseParameters.TryGetValue(machineInfoType, out ObservableCollection<BaseParameteModel> parametersData))
                        {
                            //投入地址
                            var CountAddressData = parametersData.FirstOrDefault(x => x.Name.Contains("MachineInCountAddress"));
                            var OkCountAddressData = parametersData.FirstOrDefault(x => x.Name.Contains("MachineOkCountAddress"));
                            var NgCountAddressData = parametersData.FirstOrDefault(x => x.Name.Contains("MachineNgCountAddress"));
                            var InCounst = InjMachine.ReadUInt32(CountAddressData.PLCAddress, 1);
                            var OkCounst = InjMachine.ReadUInt32(OkCountAddressData.PLCAddress, 1);
                            var NgCounst = InjMachine.ReadUInt32(NgCountAddressData.PLCAddress, 1);
                            if (InCounst != null&&  OkCounst != null && NgCounst != null)
                            {
                                //if(InCounst[0] != 0 && OkCounst[0] != 0)
                                if(InCounst[0] != 0)
                                {
                                    var _parameter = Parameter.MESCollectionItemsParameter[machineInfoType];
                                    _parameter.PutIntoNumber = (int)InCounst[0];
                                    _parameter.QualifiedNumber = (int)OkCounst[0];
                                    _parameter.UnqualifiedNumber = (int)NgCounst[0];

                                    $"{plcItem.ServiceName}【下班上传产量】获取到产量投入：{_parameter.PutIntoNumber}  OK：{_parameter.QualifiedNumber}  NG：{_parameter.UnqualifiedNumber}".RunLog(MessageLevelType.成功);
                                    try
                                    {
                                        Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                               new Dictionary<string, object>()
                                               {
                                                    { "Team", _parameter.ClassTeam },
                                                    { "Shift", _parameter.Class },
                                                    { "WorkNumber", _parameter.UserName },
                                                    { "EquipmentNo", _parameter.EquipmentCode },
                                                    { "WorkOrderNo", _parameter.WorkOrder },
                                                    { "PutIntoNumber", _parameter.InCount },
                                                    { "QualifiedNumber", _parameter.OKCount },
                                                    { "UnqualifiedNumber", _parameter.NGCount },
                                                    { "ProductionStartTime", DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss") },
                                                    { "ProductionEndTime",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },

                                                }
                                        }
                                    }
                                };
                                        Dictionary<string, object> mesParams = new Dictionary<string, object>
                                {
                                    { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                                    { "parameter", mesParameters }
                                };



                                        var result = mesData_HourInteraction.MESInteraction(Parameter.MESParameter.ProductCountDataRouter,
                                             Parameter.MESParameter.ProductCountDataTime,
                                             1, DateTime.Now, mesParams);

                                        $"{plcItem.ServiceName}【下班上传产量】生产统计小时上传MES成功投入：{_parameter.PutIntoNumber}  OK：{_parameter.QualifiedNumber}  NG：{_parameter.UnqualifiedNumber}".RunLog(MessageLevelType.成功);
                                    }
                                    catch (Exception ex)
                                    {
                                        $"{plcItem.ServiceName}【下班上传产量】生产统计小时小时小时上传MES错误：{ex}".RunLog(MessageLevelType.错误);
                                    }

                                    try
                                    {

                                        Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                            new Dictionary<string, object>(){
                                            { "Team", _parameter.ClassTeam },
                                            { "Shift", _parameter.Class },
                                            { "WorkNumber", _parameter.UserName },
                                            { "EquipmentNo", _parameter.EquipmentCode },
                                            { "WorkOrderNo", _parameter.WorkOrder },
                                            { "PutIntoNumber", _parameter.InCount },
                                            { "QualifiedNumber", _parameter.OKCount },
                                            { "UnqualifiedNumber", _parameter.NGCount },
                                            }
                                        }

                                   },
                                };

                                        Dictionary<string, object> mesParams = new Dictionary<string, object>
                                {
                                  { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                                    { "parameter", mesParameters }
                                };

                                        var result = mesData_DayInteraction.MESInteraction(Parameter.MESParameter.ProductCountData_DayRouter,
                                             Parameter.MESParameter.ProductCountData_DayTime,
                                             1, DateTime.Now, mesParams);

                                        $"{plcItem.ServiceName}【下班上传产量】生产统计天天上传MES成功投入：{_parameter.PutIntoNumber}  OK：{_parameter.QualifiedNumber}  NG：{_parameter.UnqualifiedNumber}".RunLog(MessageLevelType.成功);
                                    }
                                    catch (Exception ex)
                                    {
                                        $"{plcItem.ServiceName}【下班上传产量】生产统计天天天天上传MES错误：{ex}".RunLog(MessageLevelType.错误);
                                    }

                                    var isCount = InjMachine.Write<short>(CountAddressData.PLCAddress, new short[] { 0 });
                                    var isOkCount = InjMachine.Write<short>(OkCountAddressData.PLCAddress, new short[] { 0 });
                                    var isNgCount = InjMachine.Write<short>(NgCountAddressData.PLCAddress, new short[] { 0 });


                                    var isCount1 = InjMachine.Write<short>(CountAddressData.PLCAddress, new short[] { 0 });
                                    var isCount2 = InjMachine.Write<short>(IncrementStringNumber(CountAddressData.PLCAddress), new short[] { 0 });
                                    var isOkCount1 = InjMachine.Write<short>(OkCountAddressData.PLCAddress, new short[] { 0 });
                                    var isOkCount2 = InjMachine.Write<short>(IncrementStringNumber(OkCountAddressData.PLCAddress), new short[] { 0 });
                                    var isNgCount1 = InjMachine.Write<short>(NgCountAddressData.PLCAddress, new short[] { 0 });
                                    var isNgCount2 = InjMachine.Write<short>(IncrementStringNumber(NgCountAddressData.PLCAddress), new short[] { 0 });

                                    $"{plcItem.ServiceName}【下班】产量清零结果信息{isCount1} {isCount2} {isOkCount1} {isOkCount2} {isNgCount1} {isNgCount2}".RunLog(MessageLevelType.信息);
                                    Temporary.mesCollectionItemsTemporary[(int)machineInfoType].PutIntoNumber = 0;
                                    Temporary.mesCollectionItemsTemporary[(int)machineInfoType].QualifiedNumber = 0;
                                    Temporary.mesCollectionItemsTemporary[(int)machineInfoType].UnqualifiedNumber = 0;
                                    // $"{plcItem.ServiceName}【下班】产量清零结果信息{isCount} {isOkCount} {isNgCount}".RunLog(MessageLevelType.信息);

                                }
                                else
                                {
                                    $"{machineInfoType.ToString()}【下班】上传MES产量为零，已经上传过MES，不再重复上传".RunLog(MessageLevelType.警告);
                                }

                            }
                            else
                            {
                                sta = 0;
                                errorMachine += machineInfoType.ToString()+"、";
                               
                            }
                        }
                       
                    }
                    catch(Exception ex)
                    {
                        $"{plcItem.ServiceName}【下班上传产量】错误：{ex}".RunLog(MessageLevelType.错误);
                    }
                   
                }
            }
            if(sta==1)
            {
                _ = "下班上传产量给MES成功".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);
            }
            else
            {
                _ = $"下班上传产量给MES失败，产量获取失败，请检查设备{errorMachine}是否已经打开".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
            }
          
          
        });




        /// <summary>
        /// 预充下班调用
        /// </summary>
        public void MESCountUpLoad_Hour()
        {

            var mesData_HourInteraction = new MESProductCountData_Hour(DialogLogHelper.MesLog
            , DialogLogHelper.MESDialog);

            var mesData_DayInteraction = new MESProductCountData_Day(DialogLogHelper.MesLog
            , DialogLogHelper.MESDialog);

            var machineInfoType = MachineInfoTypes.预充装盘;

            var _parameter = Parameter.MESCollectionItemsParameter[machineInfoType];

            if(_parameter.InCount!=0&& _parameter.OKCount!=0)
            {
                $"{machineInfoType.ToString()}【下班】产量投入：{_parameter.InCount}  OK：{_parameter.OKCount}  NG：{_parameter.NGCount}".RunLog(MessageLevelType.成功);
                try
                {
                    Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                               new Dictionary<string, object>()
                                               {
                                                    { "Team", _parameter.ClassTeam },
                                                    { "Shift", _parameter.Class },
                                                    { "WorkNumber", _parameter.UserName },
                                                    { "EquipmentNo", _parameter.EquipmentCode },
                                                    { "WorkOrderNo", _parameter.WorkOrder },
                                                    { "PutIntoNumber", _parameter.InCount },
                                                    { "QualifiedNumber", _parameter.OKCount },
                                                    { "UnqualifiedNumber", _parameter.NGCount },
                                                    { "ProductionStartTime", DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss") },
                                                    { "ProductionEndTime",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },

                                                }
                                        }
                                    }
                                };
                    Dictionary<string, object> mesParams = new Dictionary<string, object>
                                {
                                    { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                                    { "parameter", mesParameters }
                                };



                    var result = mesData_HourInteraction.MESInteraction(Parameter.MESParameter.ProductCountDataRouter,
                         Parameter.MESParameter.ProductCountDataTime,
                         1, DateTime.Now, mesParams);

                    $"{machineInfoType.ToString()}【下班】生产统计小时上传MES成功投入：{_parameter.InCount}  OK：{_parameter.OKCount}  NG：{_parameter.NGCount}".RunLog(MessageLevelType.成功);
                    _parameter.InCount = 0;
                    _parameter.OKCount = 0;
                    _parameter.NGCount = 0;
                    Temporary.mesCollectionItemsTemporary[(int)machineInfoType].InCount = 0;
                    Temporary.mesCollectionItemsTemporary[(int)machineInfoType].OKCount = 0;
                    Temporary.mesCollectionItemsTemporary[(int)machineInfoType].NGCount = 0;

                }
                catch (Exception ex)
                {
                    $"{machineInfoType.ToString()}【下班】生产统计小时小时小时上传MES错误：{ex}".RunLog(MessageLevelType.错误);
                }

                try
                {


                    Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                            new Dictionary<string, object>(){
                                            { "Team", _parameter.ClassTeam },
                                            { "Shift", _parameter.Class },
                                            { "WorkNumber", _parameter.UserName },
                                            { "EquipmentNo", _parameter.EquipmentCode },
                                            { "WorkOrderNo", _parameter.WorkOrder },
                                            { "PutIntoNumber", _parameter.InCount },
                                            { "QualifiedNumber", _parameter.OKCount },
                                            { "UnqualifiedNumber", _parameter.NGCount },
                                            }
                                        }

                                   },
                                };

                    Dictionary<string, object> mesParams = new Dictionary<string, object>
                                {
                                  { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                                    { "parameter", mesParameters }
                                };

                    var result = mesData_DayInteraction.MESInteraction(Parameter.MESParameter.ProductCountData_DayRouter,
                         Parameter.MESParameter.ProductCountData_DayTime,
                         1, DateTime.Now, mesParams);

                    $"{machineInfoType.ToString()}【下班上传产量】生产统计天天上传MES成功投入：{_parameter.InCount}  OK：{_parameter.OKCount}  NG：{_parameter.NGCount}".RunLog(MessageLevelType.成功);
                    _ = "下班上传产量给MES成功".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);
                }
                catch (Exception ex)
                {
                    $"{machineInfoType.ToString()}【下班上传产量】生产统计天天天天上传MES错误：{ex}".RunLog(MessageLevelType.错误);
                }
                _parameter.InCount = 0;
                _parameter.OKCount = 0;
                _parameter.NGCount = 0;
            }else
            {
                $"{machineInfoType.ToString()}【下班】上传MES产量为零，已经上传过MES，不再重复上传，投入：{_parameter.InCount}  OK：{_parameter.OKCount}  NG：{_parameter.NGCount}".RunLog(MessageLevelType.警告);
            }

    



        }


        public string IncrementStringNumber(string str)
        {
            string prefix = str.Substring(0, 2); // 获取前缀"DM"
            string number = str.Substring(2); // 获取数字部分"50080"
            uint num = UInt32.Parse(number); // 将数字部分转换为uint
            num++; // 数字部分加1
            return prefix + num.ToString(); // 将新的数字部分和前缀拼接起来
        }
        /// <summary>
        /// 清除NG数据
        /// </summary>
        public DelegateCommand ClearStatisticsData => new DelegateCommand(() =>
        {
            var model = ObjectContainer.ResolveSingleton<HomeStatic>();
            model.ChartData.OV_AfterWeighingPassingRate.Value = 1;
            model.ChartData.AfterWeighingPassingRate = 1;
            model.ChartData.OV_LessLiquid.Value = 0;
            model.ChartData.NG_LessLiquid = 0;
            model.ChartData.OV_MultiLiquid.Value = 0; model.ChartData.NG_MultiLiquid = 0;
            model.ChartData.OV_LiquidInjection_PassingRate.Value = 1;
            model.ChartData.LiquidInjection_PassingRate = 1;
            model.ChartData.NG_ScanCode = 0;
            model.ChartData.Total_Inbound = 0;
            model.ChartData.NG_ShortCircuit = 0;
            model.ChartData.NG_BeforeWeighin = 0;
            model.ChartData.NG_FrontGlueNail = 0;
            model.ChartData.NG_RearGlueNail = 0;
            model.ChartData.NG_AfterScanCode = 0;
            model.ChartData.NG_LeakDetection = 0;
            model.ChartData.Total_LiquidInjection = 0;
            model.ChartData.Total_GlueNail = 0;
            model.ChartData.GlueNailPassingRate = 0;
            model.SaveChartData();
        });

        #region 主题相关

        private readonly PaletteHelper _paletteHelper = new PaletteHelper();

        private ColorScheme _activeScheme;
        public ColorScheme ActiveScheme
        {
            get => _activeScheme;
            set
            {
                if (_activeScheme != value)
                {
                    _activeScheme = value;
                    OnPropertyChanged();
                }
            }
        }

        private Color? _selectedColor;
        public Color? SelectedColor
        {
            get => _selectedColor;
            set
            {
                if (_selectedColor != value)
                {
                    _selectedColor = value;
                    OnPropertyChanged();
                    var currentSchemeColor = ActiveScheme switch
                    {
                        ColorScheme.Primary => _primaryColor,
                        ColorScheme.Secondary => _secondaryColor,
                        ColorScheme.PrimaryForeground => _primaryForegroundColor,
                        ColorScheme.SecondaryForeground => _secondaryForegroundColor,
                        _ => throw new NotSupportedException($"{ActiveScheme} is not a handled ColorScheme.. Ye daft programmer!")
                    };
                    if (_selectedColor != currentSchemeColor && value is Color color)
                    {
                        ChangeCustomColor(color);
                        _topicsModel.PrimaryColor = _primaryColor;
                        _topicsModel.SecondaryColor = _secondaryColor;
                        Save();
                    }
                }
            }
        }

        public IEnumerable<ISwatch> Swatches { get; } = SwatchHelper.Swatches;

        private void ChangeCustomColor(object obj)
        {
            var color = (Color)obj;

            if (ActiveScheme == ColorScheme.Primary)
            {
                _paletteHelper.ChangePrimaryColor(color);
                _primaryColor = color;
            }
            else if (ActiveScheme == ColorScheme.Secondary)
            {
                _paletteHelper.ChangeSecondaryColor(color);
                _secondaryColor = color;
            }
            else if (ActiveScheme == ColorScheme.PrimaryForeground)
            {
                SetPrimaryForegroundToSingleColor(color);
                _primaryForegroundColor = color;
            }
            else if (ActiveScheme == ColorScheme.SecondaryForeground)
            {
                SetSecondaryForegroundToSingleColor(color);
                _secondaryForegroundColor = color;
            }
        }

        private Color? _primaryColor;

        private Color? _secondaryColor;

        private Color? _primaryForegroundColor;

        private Color? _secondaryForegroundColor;

        public DelegateCommand<object> ChangeHueCommand => new DelegateCommand<object>(obj =>
        {
            var hue = (Color)obj;

            SelectedColor = hue;
            if (ActiveScheme == ColorScheme.Primary)
            {
                _paletteHelper.ChangePrimaryColor(hue);
                _primaryColor = hue;
                _primaryForegroundColor = _paletteHelper.GetTheme().PrimaryMid.GetForegroundColor();
            }
            else if (ActiveScheme == ColorScheme.Secondary)
            {
                _paletteHelper.ChangeSecondaryColor(hue);
                _secondaryColor = hue;
                _secondaryForegroundColor = _paletteHelper.GetTheme().SecondaryMid.GetForegroundColor();
            }
            else if (ActiveScheme == ColorScheme.PrimaryForeground)
            {
                SetPrimaryForegroundToSingleColor(hue);
                _primaryForegroundColor = hue;
            }
            else if (ActiveScheme == ColorScheme.SecondaryForeground)
            {
                SetSecondaryForegroundToSingleColor(hue);
                _secondaryForegroundColor = hue;
            }
        });

        private void SetPrimaryForegroundToSingleColor(Color color)
        {
            ITheme theme = _paletteHelper.GetTheme();

            theme.PrimaryLight = new ColorPair(theme.PrimaryLight.Color, color);
            theme.PrimaryMid = new ColorPair(theme.PrimaryMid.Color, color);
            theme.PrimaryDark = new ColorPair(theme.PrimaryDark.Color, color);

            _paletteHelper.SetTheme(theme);
        }

        private void SetSecondaryForegroundToSingleColor(Color color)
        {
            ITheme theme = _paletteHelper.GetTheme();

            theme.SecondaryLight = new ColorPair(theme.SecondaryLight.Color, color);
            theme.SecondaryMid = new ColorPair(theme.SecondaryMid.Color, color);
            theme.SecondaryDark = new ColorPair(theme.SecondaryDark.Color, color);

            _paletteHelper.SetTheme(theme);
        }

        public bool IsDarkTheme
        {
            get { return _topicsModel.IsDarkTheme; }
            set
            {
                _topicsModel.IsDarkTheme = value;
                _paletteHelper.ApplyBase(_topicsModel.IsDarkTheme);
                Save();
            }
        }

        private TopicsModel _topicsModel;
        private void Save() => File.WriteAllText(GlobalStatic.TopicsPath, JsonSerializer.Serialize(_topicsModel, GlobalStatic.Options), Encoding.UTF8);

        #endregion

        #region 更新模块
        /// <summary>
        /// 更新更哪里
        /// </summary>
        static string toDirectoryPath = Environment.CurrentDirectory;
        /// <summary>
        /// 主程序路径
        /// </summary>
        static string mainProgramFilePath = @$"{toDirectoryPath}\UIWindows.exe";
        /// <summary>
        /// 更新文件
        /// </summary>
        static string fromFilePath = string.Empty;

        /// <summary>
        /// 备份路径
        /// </summary>
        static string backupsDirectoryPath = @$"{new DirectoryInfo(toDirectoryPath).Parent.FullName}\WeightAppBackups";
        /// <summary>
        /// 备份排除文件,以 -x! 开头，可多个文件或文件夹
        /// </summary>
        static string backupIgnore = @$" -x!MESlog -x!logs -x!Log -x!TableData ";

        /// <summary>
        /// 更新时排除的文件,以 -x! 开头，可多个文件或文件夹
        /// </summary>
        static string updateIgnore = @$" -x!config -x!AZUpdate -x!appsettings.json ";
        /// <summary>
        /// 运行更新程序位置
        /// </summary>
        static string updateApp = @$"{toDirectoryPath}\AZUpdate\Kinlo.AZUpdate.exe";

        public DelegateCommand UpdateCmd => new DelegateCommand(() =>
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件";
            dialog.Filter = "压缩文件(*.7z;*.zip;*.rar)|*.7z;*.zip;*.rar";
            var v = dialog.ShowDialog();
            if (v == true)
            {
                var temporary = ObjectContainer.ResolveSingleton<TemporaryStatic>();
                if (temporary.IsRunStatus)
                {
                    Services.TaskService.Instance.SwitchOFF();
                    while (temporary.IsRunStatus)
                    {
                        Thread.Sleep(500);
                    }
                }

                fromFilePath = dialog.FileName;
                Process.Start(updateApp, new string[] { "1", mainProgramFilePath, fromFilePath, toDirectoryPath, backupsDirectoryPath, backupIgnore, updateIgnore });
                Environment.Exit(0);
            }
        });
        public DelegateCommand BackupCmd => new DelegateCommand(() =>
        {
            Process.Start(updateApp, new string[] { "2", mainProgramFilePath, fromFilePath, toDirectoryPath, backupsDirectoryPath, backupIgnore, updateIgnore });
        });
        public DelegateCommand RevertCmd => new DelegateCommand(() =>
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.InitialDirectory = backupsDirectoryPath;
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件";
            dialog.Filter = "压缩文件(*.7z;*.zip;*.rar)|*.7z;*.zip;*.rar";
            var v = dialog.ShowDialog();
            if (v == true)
            {
                var temporary = ObjectContainer.ResolveSingleton<TemporaryStatic>();
                if (temporary.IsRunStatus)
                {
                    Services.TaskService.Instance.SwitchOFF();
                    while (temporary.IsRunStatus)
                    {
                        Thread.Sleep(500);
                    }
                }
                fromFilePath = dialog.FileName;
                Process.Start(updateApp, new string[] { "3", mainProgramFilePath, fromFilePath, toDirectoryPath, backupsDirectoryPath, backupIgnore, updateIgnore });
                Environment.Exit(0);
            }
        });

        ManualWeight _manualWeight;
        public DelegateCommand<System.Windows.Window> TonicCommand => new DelegateCommand<System.Windows.Window>((win) =>
        {
            //打开补液窗口
            if (!IsWindowOpen<ManualWeight>())
            {
                _manualWeight = new ManualWeight();

                //显示在右下角
                double xpos = win.Left + win.Width - _manualWeight.Width - 10;
                double ypos = win.Top + win.Height - _manualWeight.Height - 10;
                _manualWeight.Left = xpos;
                _manualWeight.Top = ypos;

                _manualWeight.DataContext = new ManualWeightViewModel(Temporary, Parameter, SystemConfig, ObjectContainer.ResolveSingleton<DeviceConfigStatic>());
                _manualWeight.Show();
            }
            else
            {
                _manualWeight.Activate();
            }
        });
        
        ManualWeight _supplementaryData;
        public DelegateCommand<System.Windows.Window> SupplementaryDataCommand => new DelegateCommand<System.Windows.Window>((win) =>
        {
            //打开补液窗口
            if (!IsWindowOpen<ManualWeight>())
            {
                _supplementaryData = new ManualWeight();

                //显示在右下角
                double xpos = win.Left + win.Width - _supplementaryData.Width - 10;
                double ypos = win.Top + win.Height - _supplementaryData.Height - 10;
                _supplementaryData.Left = xpos;
                _supplementaryData.Top = ypos;

                _supplementaryData.DataContext = new ManualWeightViewModel(Temporary, Parameter, SystemConfig, ObjectContainer.ResolveSingleton<DeviceConfigStatic>());
                _supplementaryData.Show();
            }
            else
            {
                _manualWeight.Activate();
            }
        });


        //SupplementaryDataView _supplementaryDataView;
        //public DelegateCommand ShowRestoreDataCMD => new DelegateCommand(() =>
        //{
        //    if (!IsWindowOpen<ManualWeight>())
        //    {
        //        _supplementaryDataView = new SupplementaryDataView();
        //        _supplementaryDataView.DataContext = new SupplementaryDataViewModel(_displayItems, Parameter, Temporary);
        //        _supplementaryDataView.Show();
        //    }
        //    else
        //    {
        //        _supplementaryDataView.Activate();
        //    }
        //});

        
        public static bool IsWindowOpen<T>(string name = null) where T : System.Windows.Window
        {
            var windows = System.Windows.Application.Current.Windows.OfType<T>();
            return string.IsNullOrEmpty(name) ?
             System.Windows.Application.Current.Windows.OfType<T>().Any() :
             System.Windows.Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name));
        }
        #endregion
    }
}
